package com.zdl.netutils.http

import android.os.Environment
import com.zdl.netutils.http.DownFileJava.getNameFromUrl
import okhttp3.ResponseBody
import okio.Okio
import retrofit2.Response
import java.io.File
import java.io.IOException

object DownFileKotlin {


    public fun writeResponseBodyToDisk2(url: String, saveDir: String, response: Response<ResponseBody>, downloadListener: DownloadListener) {
        val saveFolder = isExistDir(saveDir)
        val tempPath = saveFolder + File.separator + getNameFromUrl(url)
        try {
            val responseBody = response.body()
            FileUtils.deleteFile(tempPath)
            val ApkFile = File(tempPath)
            var current: Long = 0
            var len: Long = 0
            val bufferSize: Long = 200 * 1024 //200kb
            val sink = Okio.buffer(Okio.sink(ApkFile))
            val buffer = sink.buffer()//输出文件流
            val total = responseBody!!.contentLength()//文件长度
            val source = responseBody.source()//文件流
            while ({ len = source.read(buffer, bufferSize);len }() > 0) {
                current += len
                sink.emit()
                val progress = (current * 1.0f / total * 100).toLong()
                downloadListener.onDownloading(progress)
            }
            source.close()
            sink.close()
            downloadListener.onDownloadSuccess(tempPath)
        } catch (e: IOException) {
            downloadListener.onDownloadFailed()
        }
    }

    @Throws(IOException::class)
    private fun isExistDir(saveDir: String): String {
        // 下载位置
        val downloadFile = File(Environment.getExternalStorageDirectory(), saveDir)
        if (!downloadFile.mkdirs()) {
            downloadFile.createNewFile()
        }
        return downloadFile.absolutePath
    }
}